package com.tul.exercise.base.swing.event;

import com.tul.exercise.base.swing.SwingConsole;
import com.tul.exercise.base.utils.Print;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Description 《java编程思想》第22章 示例12：
 * <p>
 * 事件示例：显示
 **/
public class ShowAddListeners extends JFrame {
    private JTextField name = new JTextField(25);
    private JTextArea results = new JTextArea(40, 65);

    private static Pattern addListener = Pattern.compile("(add\\w+?Listener\\(.*?\\))");
    private static Pattern qualifier = Pattern.compile("\\w+\\.");

    private ActionListener nameListener = (ActionEvent e) -> actionPerformed(e);

    /**
     * 事件监听函数
     * @param e 事件
     */
    public void actionPerformed(ActionEvent e) {
        String nm = name.getText().trim();
        if (nm.length() == 0) {
            results.setText("No match");
            return;
        }

        Class<?> kind;
        try {
            kind = Class.forName("javax.swing." + nm);
        } catch (ClassNotFoundException ex) {
            results.setText("No match");
            return;
        }

        Method[] methods = kind.getMethods();
        results.setText("");

        for (Method m : methods) {
            Matcher matcher = addListener.matcher(m.toString());

            Print.print(m.toString());
            if (matcher.find()) {

                Print.print(matcher.group(1));
                results.append(qualifier.matcher(matcher.group(1)).replaceAll("") + "\n");
            }
        }
    }


    public ShowAddListeners() {
        name.addActionListener(nameListener);

        JPanel top = new JPanel();
        top.add(new JLabel("Swing class name (press Enter)"));
        top.add(name);
        add(BorderLayout.NORTH, top);
        add(new JScrollPane(results));

        name.setText("JTextArea");
        nameListener.actionPerformed(new ActionEvent("", 0, ""));
    }

    public static void main(String[] args) {
        SwingConsole.run(new ShowAddListeners(), 500, 400);
    }
}














